package com.example.client_rpc.controller;

import com.example.client_rpc.config.RabbitConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

@RestController
public class HelloController {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public void hello(String msg){

        Message sendMsg = MessageBuilder.withBody(msg.getBytes()).build();
        //发送消息：交换机，要放到哪个queue去发（sendQueue），要发送的msg
        Message response = rabbitTemplate.sendAndReceive(RabbitConfig.RPC_EXCHANGE_NAME,RabbitConfig.RPC_MSG_SEND_QUEUE,sendMsg);//send后等待响应
        //返回值：server给的响应
        if (response!=null){
            //发送消息的correlationId
            String sendMsgCorrelationId = sendMsg.getMessageProperties().getCorrelationId();

            //响应的correlationId (服务端会手动设置CorrelationId，跟发来的message的correlationID一样) !!!!!!
            String recMsgCorrelationId = (String) response.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
            if (sendMsgCorrelationId.equals(recMsgCorrelationId)){ //no ==
                System.out.println("from server response:"+response.getBody());
            }else{
                System.out.println("No related message");
            }
        }else{
            System.out.println("response is null");
        }
    }

}
